<template>
  <div class="detail" v-if="detail">
    <!-- 主图轮播 -->
    <van-swipe :autoplay="3000" :width="375">
      <van-swipe-item v-for="photo in detail.photo" :key="photo.id">
        <img v-lazy="photo.url" :style="{width: '100%'}" />
      </van-swipe-item>
    </van-swipe>

    <!-- 标题 -->
    <div class="detail-title">{{detail.title}}</div>
    <!-- 价格 -->
    <div>￥{{detail.price | money}}</div>

    <!-- 图文详情 -->
    <van-divider>图文详情</van-divider>
    <div>
      <van-image
        width="375"
        lazy-load
        v-for="content in detail.descContentList"
        :key="content.id"
        :src="content.photo.url"
      />
    </div>

    <!-- 商品导航 -->
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" />
      <van-goods-action-icon icon="cart-o" text="购物车" @click="$router.push('/cart')" />
      <van-goods-action-icon icon="shop-o" text="店铺" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addToCart" />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>
  </div>
</template>

<script>
import { getDetail } from '@/api/detail'
export default {
  name: 'Detail',
  data() {
    return {
      detail: null,
    }
  },
  created() {
    console.log(this)
    getDetail(this.$route.query.id)
      .then(data => {
        this.detail = data.detail
      })
  },
  methods: {
    // 加入购物车
    addToCart() {
      console.log('加入购物车')
      // 构建当前选购商品对象
      const { id, title, image, price, introduction } = this.detail
      const curr = {
        id,
        title,
        image,
        price,
        desc: introduction,
        amount: 1,
      }
      // 将当前选购商品保存到购物车数组中
      // 调用 mutation 方法来实现状态更新.
      // 在组件中不能直接调用到 mutation 方法，而是需要调用
      // this.$store.commit('mutationName', payload) 来提交 mutation
      this.$store.commit('add', curr)

      console.log('添加成功：', this.$store.state.cart)
    },
  },
}
</script>

<style lang="less" scoped>
  /deep/ .van-image {
    display: block;
  }
</style>
